//package cn.cdutetc.foxwatch.controller.chat;
//
//
//import com.alibaba.dashscope.aigc.multimodalconversation.*;
//import com.alibaba.dashscope.common.MultiModalMessage;
//import com.alibaba.dashscope.common.Role;
//import com.alibaba.dashscope.exception.ApiException;
//import com.alibaba.dashscope.exception.NoApiKeyException;
//import com.alibaba.dashscope.exception.UploadFileException;
//import com.alibaba.dashscope.utils.JsonUtils;
//import io.reactivex.Flowable;
//import io.swagger.v3.oas.annotations.Operation;
//import io.swagger.v3.oas.annotations.tags.Tag;
//import jakarta.servlet.http.HttpServletResponse;
//import org.springframework.web.bind.annotation.*;
//import reactor.core.publisher.Flux;
//import reactor.core.publisher.Mono;
//
//import java.io.IOException;
//import java.io.OutputStream;
//import java.nio.charset.StandardCharsets;
//import java.time.Duration;
//import java.util.ArrayList;
//import java.util.Arrays;
//import java.util.Collections;
//import java.util.List;
//
///**
// * 该接口已废弃
// * 原因：uniapp开发安卓只接受流式只能使用websocket，请移步至websocket接口
// * 但web端可以使用fetch或者EventSource接口进行实时通信
// */
//@Tag(name = "AI Chat")
//@RestController
//@RequestMapping("/ai")
//public class AiController {
//
//    public static void simpleMultiModalConversationStreamCall() throws ApiException, NoApiKeyException, UploadFileException {
//        MultiModalConversation conv = new MultiModalConversation();
//        MultiModalMessageItemText systemText = new MultiModalMessageItemText("You are an AI Psychological counselor,and your name is 心理咨询师, Remember your identity, you can only answer questions related to psychology,。");
//        MultiModalConversationMessage systemMessage = MultiModalConversationMessage.builder()
//                .role(Role.SYSTEM.getValue()).content(Arrays.asList(systemText)).build();
//        MultiModalMessageItemText userText = new MultiModalMessageItemText("你是谁?");
//        MultiModalConversationMessage userMessage =
//                MultiModalConversationMessage.builder().role(Role.USER.getValue())
//                        .content(Arrays.asList(userText)).build();
//        List<MultiModalConversationMessage> messages = new ArrayList<>();
//        messages.add(systemMessage);
//        messages.add(userMessage);
//        MultiModalConversationParam param = MultiModalConversationParam.builder()
//                .model(MultiModalConversation.Models.QWEN_VL_CHAT_V1)
//                .messages(messages)
//                .build();
//        MultiModalConversationResult result = conv.call(param);
//        System.out.println(result);
//        MultiModalMessageItemText assistentText = new MultiModalMessageItemText(
//                result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text").toString());
//        MultiModalConversationMessage assistentMessage = MultiModalConversationMessage.builder()
//                .role(Role.ASSISTANT.getValue()).content(Arrays.asList(assistentText)).build();
//        messages.add(assistentMessage);
//        userText = new MultiModalMessageItemText("你是通义千问吗？");
//        messages.add(MultiModalConversationMessage.builder().role(Role.USER.getValue())
//                .content(Arrays.asList(userText)).build());
//        param.setMessages(new ArrayList<Object>(messages));
//        result = conv.call(param);
//        System.out.print(result);
//    }
//
//    public static void main(String[] args) {
//        try {
//            simpleMultiModalConversationCall();
//        } catch (ApiException | NoApiKeyException | UploadFileException e) {
//            System.out.println(e.getMessage());
//        }
//        System.exit(0);
//    }
//
//    public static void simpleMultiModalConversationCall()
//            throws ApiException, NoApiKeyException, UploadFileException {
//        MultiModalConversation conv = new MultiModalConversation();
//        MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
//                .content(Arrays.asList(
//                        Collections.singletonMap("image", "https://prod-chat-kimi.tos-s3-cn-beijing.volces.com/prod-chat-kimi/cou7r32vk6gfi4v1dn00/2024-09-20/crmjh8cubms8lg7ijpf0/test-left.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKLTYTJlNjgwMjY2ZDBkNDFiYmI5YWNiZDBlZmFmYjIzZTA%2F20240920%2Fcn-beijing%2Fs3%2Faws4_request&X-Amz-Date=20240920T085601Z&X-Amz-Expires=518400&X-Amz-SignedHeaders=host&X-Amz-Signature=7ddd40a6b8ddd29cca8835a6cbe6c79357bfdd87e86f903760ce3b3a85b6436b"),
//                        Collections.singletonMap("text", "输出markdown表格?"))).build();
//        MultiModalConversationParam param = MultiModalConversationParam.builder()
//                .model("qwen-vl-max")
//                .message(userMessage)
//                .build();
//        MultiModalConversationResult result = conv.call(param);
//        result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text");
//        System.out.println(JsonUtils.toJson(result));
//
//    }
//
//    @Operation(summary = "chat")
//    @PostMapping("/chat")
//    public Flux<String> chatA(String sendMessage, HttpServletResponse rsp) throws NoApiKeyException, UploadFileException {
//        rsp.setHeader("Content-Type", "application/octet-stream");
//        MultiModalConversation conv = new MultiModalConversation();
//        MultiModalMessageItemText systemText = new MultiModalMessageItemText("You are an AI Psychological counselor,and your name is 心理咨询师, Remember your identity, you can only answer questions related to psychology,。");
//        MultiModalConversationMessage systemMessage = MultiModalConversationMessage.builder()
//                .role(Role.SYSTEM.getValue()).content(Arrays.asList(systemText)).build();
//        //构建用户消息
//        MultiModalMessageItemText userText = new MultiModalMessageItemText(sendMessage);
//        MultiModalConversationMessage userMessage =
//                MultiModalConversationMessage.builder().role(Role.USER.getValue())
//                        .content(Arrays.asList(userText)).build();
//        //放入消息列表
//        List<MultiModalConversationMessage> messages = new ArrayList<>();
//        messages.add(systemMessage);
//        messages.add(userMessage);
//        //选择模型
//        MultiModalConversationParam param = MultiModalConversationParam.builder()
//                .model(MultiModalConversation.Models.QWEN_VL_CHAT_V1)
//                .messages(messages)
//                .build();
////        MultiModalConversationResult result = conv.call(param);
//
////        System.out.println(result);
////        MultiModalMessageItemText a
////        ssistentText = new MultiModalMessageItemText(
////                result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text").toString());
////        MultiModalConversationMessage assistentMessage = MultiModalConversationMessage.builder()
////                .role(Role.ASSISTANT.getValue()).content(Arrays.asList(assistentText)).build();
////        messages.add(assistentMessage);
////        userText = new MultiModalMessageItemText("你是通义千问吗？");
////        messages.add(MultiModalConversationMessage.builder().role(Role.USER.getValue())
////                .content(Arrays.asList(userText)).build());
////        param.setMessages(new ArrayList<Object>(messages));
////        result = conv.call(param);
//        Flowable<MultiModalConversationResult> result = conv.streamCall(param);
//        result.blockingForEach(item -> {
//            System.out.println(item);
//        });
//        String message = "123123123123123";
//        return Flux.fromStream(Arrays.stream(message.split("")))
//                .delayElements(Duration.ofMillis(300));  // 每个字符延迟300毫秒
//    }
//
//    //sse接口
//    @Operation(summary = "流式响应")
//    @GetMapping("/chat-new")
//    public Mono<Void> chat(@RequestParam String sendMessage, HttpServletResponse response) throws NoApiKeyException, UploadFileException, IOException {
//        System.out.println(sendMessage);
//
//        // 设置响应头信息
//        response.setContentType("text/event-stream");
//        response.setCharacterEncoding("UTF-8");
//        response.setHeader("Cache-Control", "no-cache");
//        response.setHeader("X-Accel-Buffering", "no");
//        response.setHeader("Connection", "keep-alive");
//
//        // 初始化对话
//        MultiModalConversation conv = new MultiModalConversation();
//        MultiModalMessageItemText systemText = new MultiModalMessageItemText("You are an AI Psychological counselor, and your name is 心理咨询师. Remember your identity, you can only answer questions related to psychology.");
//        MultiModalConversationMessage systemMessage = MultiModalConversationMessage.builder()
//                .role(Role.SYSTEM.getValue()).content(Arrays.asList(systemText)).build();
//        MultiModalMessageItemText userText = new MultiModalMessageItemText(sendMessage);
//        MultiModalConversationMessage userMessage = MultiModalConversationMessage.builder()
//                .role(Role.USER.getValue()).content(Arrays.asList(userText)).build();
//        List<MultiModalConversationMessage> messages = new ArrayList<>();
//        messages.add(systemMessage);
//        messages.add(userMessage);
//        MultiModalConversationParam param = MultiModalConversationParam.builder()
//                .model(MultiModalConversation.Models.QWEN_VL_CHAT_V1)
//                .messages(messages)
//                .build();
//
//        // 获取数据流
//        Flowable<MultiModalConversationResult> resultFlowable = conv.streamCall(param);
//        OutputStream outputStream = response.getOutputStream();
//
//        // 发送数据流
//        return Flux.from(resultFlowable)
//                .flatMap(result -> {
//                    String text = result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text").toString();
//                    System.out.println(text);
//                    // 构建SSE数据格式
//                    String sseData = "data: " + text + "\n\n";
//
//                    // 发送到前端
//                    return Mono.fromRunnable(() -> {
//                        try {
//                            outputStream.write(sseData.getBytes(StandardCharsets.UTF_8));
//                            outputStream.flush();
//                        } catch (IOException e) {
//                            throw new RuntimeException("Failed to write to output stream", e);
//                        }
//                    });
//                })
//                .then(Mono.fromRunnable(() -> {
//                    try {
//                        // 发送结束信号
//                        String endSignal = "data: end" + "\n\n";
//                        outputStream.write(endSignal.getBytes(StandardCharsets.UTF_8));
//                        outputStream.flush();
//                        outputStream.close(); // 关闭输出流
//                    } catch (IOException e) {
//                        throw new RuntimeException("Failed to send end signal", e);
//                    }
//                }));
//    }
//}
//
